﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

namespace MatrixControls
{
	[DefaultEvent("Click")]
	public partial class ColorBox: UserControl
    {
		private int boxsize      = 20;
		private Color color_fill = Color.White;

		private Color color_border_1, color_border_2;
		private readonly Color color_border_normal_1 = Color.FromArgb(160, 160, 160);
		private readonly Color color_border_normal_2 = Color.White;
		private readonly Color color_border_hover_1  = Color.FromArgb(100, 165, 231);
		private readonly Color color_border_hover_2  = Color.FromArgb(203, 228, 253);


		public ColorBox()
        {
            InitializeComponent();

			SetStyle(ControlStyles.AllPaintingInWmPaint, true);
			SetStyle(ControlStyles.UserPaint, true);

			color_border_1 = color_border_normal_1;
			color_border_2 = color_border_normal_2;
			BoxSize        = boxsize;
		}


		#region 控件属性
		[Browsable(false)]
		[EditorBrowsable(EditorBrowsableState.Never)]
		public new Size Size { get; set; }

		[Category("外观")]
		[Description("盒子尺寸大小")]
		public int BoxSize
		{
			get { return boxsize; }
			set
			{
				if (value < 20)
					throw new ArgumentException("BoxSize 不能小于 20 像素");

				Width = Height = boxsize = value;
				Invalidate();
			}
		}

		[Category("外观")]
		[Description("盒子填充颜色")]
		public Color BoxColor
		{
			get { return color_fill; }
			set
			{
				color_fill = value;
				Invalidate();
			}
		}

		[Category("数据")]
		[Description("盒子索引序号")]
		public int Index { get; set; } = 0;
		#endregion


		#region 窗体控件事件
		private void ColorBox_MouseLeave(object sender, EventArgs e)
		{
			color_border_1 = color_border_normal_1;
			color_border_2 = color_border_normal_2;

			Invalidate();
		}

		private void ColorBox_MouseEnter(object sender, EventArgs e)
		{
			color_border_1 = color_border_hover_1;
			color_border_2 = color_border_hover_2;

			Invalidate();
		}

		protected override void OnPaint(PaintEventArgs e)
		{
			base.OnPaint(e);

			BufferedGraphicsContext buffer_context = BufferedGraphicsManager.Current;
			BufferedGraphics buffer = buffer_context.Allocate(e.Graphics, e.ClipRectangle);
			Graphics graphics = buffer.Graphics;

			graphics.DrawRectangle(
				new Pen(color_border_1),
				new Rectangle(0, 0, boxsize - 1, boxsize - 1)
			);
			graphics.DrawRectangle(
				new Pen(color_border_2, 2),
				new Rectangle(2, 2, boxsize - 4, boxsize - 4)
			);
			graphics.FillRectangle(
				new SolidBrush(color_fill),
				new Rectangle(3, 3, boxsize - 6, boxsize - 6)
			);

			buffer.Render(e.Graphics);
			buffer.Dispose();
			graphics.Dispose();
		}
		#endregion
	}
}
